<?php
/**
 * 约课记录
 * @author 鸣枫
 *
 */
error_reporting(E_ALL ^ E_NOTICE);
class Courserecord extends CT_Controller{
    
    private $member_id;     //用户ID
    
    function __construct() {
        parent::__construct();
        
        $this->load->model('book_model');
        $this->load->model('teacher_model');
        $this->member_id = $this->_uid;
        //$this->member_id = 1;
        
        
		if(!$this->member_id && !$this->input->is_ajax_request()){
            redirect('/login');
        }
    }
    
    const SIZE = 5;        //分页显示数量
    
    /**
     * 约课列表
     */
    public function index(){       
        try {
            //自动确认上课
            $this->AutoClassBegins();
            //超过3天不点击下课自动下课
            $this->AutoClassEnd();
            
            $type = intval($this->input->get('type'));    //类型
            $this->load->helper("arraytool");   //加载工具
            $this->load->model('Book_model');
            $fild = '(case `status` when 3 then 7 else status end) as ob_status,id as book_id,teacher_id,book_member_id,course_package_id,status,book_date,book_date_start';
            $where = " member_id = {$this->member_id} and nursery_id ={$this->_nursery_id}";
            $where = " member_id = {$this->member_id}";
            $order_by = "ob_status asc, update_date desc" ;
            switch ($type){
                case 1:     //等待上课
                    $where .= ' AND status = 0 ';
                    break;
                case 2:     //已经下课
                    $where .= ' AND status in(2,5) ';
                    break;
                default:
                    $where .= ' AND status != 4 ';
                    break;
            }
            
            $book_list = $this->Book_model->findAll($where,$fild,$order_by);
            if($book_list){
            
                //获取课包信息
                $this->load->model('Course_Package_model');
                $fild = 'id,title as book_title,logo as book_logo';
                $where = " id IN ( ". filterValue($book_list,'course_package_id',true) ." )";
                $course_package_list = $this->Course_Package_model->findAll($where,$fild);
                $course_package_list = restByKey($course_package_list,'id');
                $book_list = arrayMerge($book_list,'course_package_id',$course_package_list);   //合并
                
                //获取教师信息
                $this->load->model('Teacher_model');
                $fild = 'id,name as teacher_name,avatar as teacher_avatar';
                $where = " id IN ( " . filterValue($book_list,'teacher_id',true) . ")";
                $teacher_list = $this->Teacher_model->findAll($where,$fild);
                $teacher_list = restByKey($teacher_list,'id');
                $book_list = arrayMerge($book_list,'teacher_id',$teacher_list);   //合并
                            
                //获取用户信息
                $this->load->model('Book_Member_model');
                $fild = 'id as address_id,address';
                $where = " id IN ( " . filterValue($book_list,'book_member_id',true) .")";
                $book_member_list = $this->Book_Member_model->findAll($where,$fild);
                $book_member_list = restByKey($book_member_list,'address_id');
                $book_list = arrayMerge($book_list,'book_member_id',$book_member_list);   //合并
                
                //获取是否评价状态
                $this->load->model('Book_evaluate_model');
                $where = " book_id IN (". filterValue($book_list,'book_id',true) .") AND member_id = '$this->member_id' ";
                $book_evaluate_list = $this->Book_evaluate_model->findAll($where,'book_id');
                $book_evaluate_list = restByKey($book_evaluate_list,'book_id');
                
                foreach ($book_list as $key=>$val){
                    $book_list[$key]['evaluate'] = 0;
                    if(!empty($book_evaluate_list[$val['book_id']]))
                        $book_list[$key]['evaluate'] = 1;
                }
            }
            
            $this->ct_template->write('_title', '约课记录');
            $this->ct_template->write_view('content', 'courserecord/index',array(
                'book_list'    =>  $book_list,
                'weekArr'    =>  array("周日","周一","周二","周三","周四","周五","周六"),
                'type'  =>  $type,
            ), FALSE);
            $this->ct_template->render();
            
            
        }catch (Exception $e){
            $this->ct_template->write('_title', '错误提示');
            $this->ct_template->write_view('content', 'errors/html/warn', array('msg'=>$e->getMessage() ), FALSE);
            $this->ct_template->render();
        }
        
    }
    
    /**
     * 自动确认上课
     */
    public function AutoClassBegins(){
        $this->load->model('Book_model');
        $where = 'member_id = '.$this->member_id;
        $where.= ' AND status = 0 ';
        $where.= " AND book_date <= '" . date('Y-m-d') ."'";
        $where.= " AND book_date_start <= '" .date('H:i:s')."'";
        
        $this->Book_model->update(array('status'=>1),$where);
    }
    
    /**
     * 超过3天不点击下课自动下课
     */
    public function AutoClassEnd(){
        $this->load->model('Book_model');
        $where = 'member_id = '.$this->member_id;
        $where.= ' AND status in(1,5,6) ';
        $where.= ' AND UNIX_TIMESTAMP(create_date)+60*60*24*3 <='.time().' ';
        
        $this->Book_model->update(array('status'=>2),$where);
    }
    
    /**
     * 约课详情
     */
    public function courseinfo(){
        try {
            $book_id = intval($this->input->get('book_id'));    //约课ID
            if(empty($book_id))throw new Exception('约课ID为空');
                        
            //$this->load->helper("arraytool");   //加载工具
            $this->load->model('Book_model');
            $fild = 'id as book_id,book_member_id,teacher_id,course_package_id,status,book_date,book_date_start,hours,order_id,message';           
            $where = array();
            $where['id'] = $book_id;
            $where['member_id'] = $this->member_id;
            $book_info = $this->Book_model->find($where,$fild);
            if(empty($book_info))   throw new Exception('没有约课记录');
            
            //获取课包信息
            $this->load->model('Course_Package_model');
            $fild = 'id,title as book_title,logo as book_logo';
            $where = array();
            $where['id'] = $book_info['course_package_id'];
            $course_package_info = $this->Course_Package_model->find($where,$fild);
                        
            //获取教师信息
            $this->load->model('Teacher_model');
            $fild = 'id,name as teacher_name,avatar as teacher_avatar';
            $where = array();
            $where['id'] = $book_info['teacher_id'];
            $teacher_info = $this->Teacher_model->find($where,$fild);
                        
            //获取用户信息
            $this->load->model('Book_Member_model');
            $fild = 'id,address';
            $where = array();
            $where['id'] = $book_info['book_member_id'];
            $book_member_info = $this->Book_Member_model->find($where,$fild);
            
            $book_info = array_merge($book_info,$course_package_info,$teacher_info,$book_member_info);  //合并
            
            $book_info['evaluate'] = $this->evaluatelist(); //获取评价列表
            
            $this->ct_template->write('_title', '约课详情');
            $this->ct_template->write_view('content', 'courserecord/info',array(
                'book_info'    =>  $book_info,
                'weekArr'    =>  array("周日","周一","周二","周三","周四","周五","周六"),
                'type'  =>  array('等待上课','上课中','已下课','已结束','已取消'),
            ), FALSE);
            $this->ct_template->render();
                    
        }catch (Exception $e){
            $this->ct_template->write('_title', '错误提示');
            $this->ct_template->write_view('content', 'errors/html/warn', array('msg'=>$e->getMessage() ), FALSE);
            $this->ct_template->render();
        }
        
    }
    /**
     * 获取评价列表
     */
    private function evaluatelist(){
        try {
            $book_id = intval($this->input->get('book_id'));   //约课ID
            if(empty($book_id))throw new Exception('约课ID为空');
            
            
            $this->load->model('Book_Evaluate_model');
            $fild = 'id,star,message,create_date';
            $where = array();
            $where['status'] = 1;
            $where['book_id'] = $book_id;
            $where['member_id'] = $this->member_id;
            
            $book_evaluate_list = $this->Book_Evaluate_model->findAll($where,$fild);
            if(empty($book_evaluate_list))throw new Exception('没有评论列表');
            
            return $book_evaluate_list;
        }catch (Exception $e){
            return array();
        }
    }
    /**
     * 提交评价
     */
    public function evaluate(){
        try {
            $book_id = intval($this->input->get('book_id'));    //约课ID
            if(empty($book_id))throw new Exception('约课ID为空');
            $star = intval($this->input->get('star'));       //分数
            if($star < 1)$star = 1;
            if($star > 5)$star = 5;
            $message = $this->input->get('message',TRUE);    //内容
            if(empty($message))throw new Exception('评价内容为空');
            
            $this->load->model('Book_model');
            $fild = 'id,teacher_id,course_package_id,status';
            $where = array();
            $where['id'] = $book_id;
            $where['member_id'] = $this->member_id;
            $book_info = $this->Book_model->find($where,$fild);
            if(empty($book_info) || !in_array($book_info['status'],array(2,5)))
                throw new Exception('没有约课记录,或课程未结束');
            //查询是否已评价过
            $this->load->model('Book_Evaluate_model');
            $fild = 'id';
            $where = array();
            $where['status'] = 1;
            $where['book_id'] = $book_id;
            $where['member_id'] = $this->member_id;
            $book_evaluate_info = $this->Book_Evaluate_model->find($where,$fild);
            if(!empty($book_evaluate_info))throw new Exception('请勿重复评价');
            
            //插入数据
            $data = array();
            $data['book_id'] = $book_id;
            $data['member_id'] = $this->member_id;
            $data['teacher_id'] = $book_info['teacher_id'];
            $data['course_package_id'] = $book_info['course_package_id'];
            $data['star'] = $star;
            $data['message'] = $message;
            $data['create_date'] = date('Y-m-d H:i:s');
            $bool = $this->Book_Evaluate_model->insert($data);
            if(empty($bool))throw new Exception('评论失败');
            
            if($book_info['status'] == 2){
                //修改状态
                $where = array();
                $where['id'] = $book_id;
                $where['member_id'] = $this->member_id;
                
                $data = array();
                $data['status'] = 3;
                $data['update_date'] = date('Y-m-d H:i:s');
                $bool = $this->Book_model->update($data,$where);
                if(empty($bool))throw new Exception('修改失败');
            }
            
            redirect("/courserecord/");
            
        }catch (Exception $e){
            $this->ct_template->write('_title', '错误提示');
            $this->ct_template->write_view('content', 'errors/html/warn', array('msg'=>$e->getMessage() ), FALSE);
            $this->ct_template->render();
        }
        
    }
    /**
     * 下课
     */
    public function classover(){
        try {
            $book_id = intval($this->input->get('book_id'));    //约课ID
            if(empty($book_id))throw new Exception('约课ID为空');
            
            $this->load->model('Book_model');
            $fild = 'id,teacher_id,course_package_id,status';
            $where = array();
            $where['id'] = $book_id;
            $where['member_id'] = $this->member_id;
            $where['status in(1,6)'] = NULL;
            $book_info = $this->Book_model->find($where,$fild);
            if(empty($book_info))throw new Exception('没有约课记录');
            
            //修改状态
            $data = array();
            if($book_info['status'] == 1){
                $data['status'] = 5;
            }else{
                $data['status'] = 2;
            }
            
            $data['update_date'] = date('Y-m-d H:i:s');
            $bool = $this->Book_model->update($data,$where);
            if(empty($bool))throw new Exception('修改失败');
            
            $this->ct_template->write('_title', '取消');
            $this->ct_template->write_view('content', 'courserecord/classover',array(
                'book_id'   =>  $book_id,
            ), FALSE);
            $this->ct_template->render();
            
        }catch (Exception $e){
            $this->ct_template->write('_title', '错误提示');
            $this->ct_template->write_view('content', 'errors/html/warn', array('msg'=>$e->getMessage() ), FALSE);
            $this->ct_template->render();
        }
        
    }
    /**
     * 取消预约
     */
    public function classcancel(){
            try {
            $book_id = intval($this->input->get('book_id'));    //约课ID
            if(empty($book_id))throw new Exception('约课ID为空');
            
            $this->load->model('Book_model');
            $fild = 'id,teacher_id,course_package_id,status';
            $where = array();
            $where['id'] = $book_id;
            $where['member_id'] = $this->member_id;
            $where['status'] = 0;
            $book_info = $this->Book_model->find($where,$fild);
            if(empty($book_info))throw new Exception('没有约课记录');
            
            //修改状态
            $data = array();
            $data['status'] = 4;
            $data['update_date'] = date('Y-m-d H:i:s');
            $bool = $this->Book_model->update($data,$where);
            if(empty($bool))throw new Exception('修改失败');
            
            //课时增加
            $this->load->model('Order_model');
            $sql = "update `order` set `surplus_hours` = `surplus_hours` + {$book_info['hours']} where id = '{$book_info['order_id']}' ";
            $this->Order_model->query($sql);
            
            //预约列表减少预约总数
            $this->load->model('Course_package_model');
            $course_package_info = $this->Course_package_model->find(array('id'=>$book_info['course_package_id']));
            if($course_package_info){
                $this->load->model('Course_list_model');
                $sql = "update `course_list` set `total_book` = `total_book` - {$book_info['hours']} where id = '{$course_package_info['course_list_id']}' ";
                $this->Course_list_model->query($sql);
            }
            
            //减少老师上课次数
            $this->load->model('Teacher_model');
            $sql = "update `teacher` set `book_num` = `book_num` - {$book_info['hours']} where id = '{$book_info['teacher_id']}' ";
            $this->Teacher_model->query($sql);
            
            $this->ct_template->write('_title', '取消');
            $this->ct_template->write_view('content', 'courserecord/classcancel',array(
            
            ), FALSE);
            $this->ct_template->render();
            
        }catch (Exception $e){
            $this->ct_template->write('_title', '错误提示');
            $this->ct_template->write_view('content', 'errors/html/warn', array('msg'=>$e->getMessage() ), FALSE);
            $this->ct_template->render();
        }
        
    }
    /**
     * 重置预约
     */
    public function Resetbook(){
    	try {
    	    $this->load->model('book_model');
    	    $this->load->model('teacher_model');
    	    
    		$book_id = intval($_REQUEST['book_id']);
    		if(empty($book_id))throw new Exception('ID为空');
    		$book_info = $this->book_model->find(array('id'=>$book_id));
    		if(empty($book_info))throw new Exception('不存在');
    			
    		$form_submit = $this->input->post('form_submit');
    		if(!empty($form_submit)){	
    			
    			$this->load->model('reset_book_model');
    			$bool = $this->reset_book_model->insert(array(
    					'admin_id'	=>	$this->member_id,
    					'book_id'	=>	$book_id,
    					'teacher_id'	=>	$book_info['teacher_id'],
    					'hours'		=>	1,
    					'book_date'	=>	$book_info['book_date'],
    					'book_date_start'	=>	$book_info['book_date_start'],
    					'book_date_end'	=>	$book_info['book_date_end'],
    					'create_date'	=>	date('Y-m-d H:i:s'),
    			));
    
    			if(empty($bool))throw new Exception('错误');
    			$book_time = explode('~',$_REQUEST['time']);
    			$this->book_model->update(array(
    					'teacher_id'	=>	$_REQUEST['hi_teacher_id'],
    					'book_date'		=>	mb_substr($_REQUEST['date'],0,10,'utf-8'),
    					'book_date_start'	=>	$book_time[0],
    					'book_date_end'		=>	$book_time[1],
    			),array('id'=>$book_id));
    
    			redirect("courserecord");
    			//$this->pr($_REQUEST);
    
    		}
    		$where = array(
    			'nursery_id'=> $book_info['nursery_id'],
    			'status'    =>1,
    		);
    		//获取教师信息
    		$teacher_info = $this->teacher_model->find(array('id'=>$book_info['teacher_id']),'id,name,avatar');
    		$teacher_list = $this->teacher_model->findAll($where,'id,name,avatar,book_num,explain');
    		if(empty($teacher_list))throw new Exception('教师列表为空');

     		$weekArr=array("周日","周一","周二","周三","周四","周五","周六");
     		$w = date('w',strtotime($book_info['book_date']));
     		$book_info['book_date'] .= "（{$weekArr[$w]}）";
    		
    			
    		$this->ct_template->write_view('content', 'courserecord/resetbook', array(
    				'book_info'	=>	$book_info,
    				'book_id'	=>	$book_id,
    				'teacher_info'	=>	$teacher_info,
    				'teacher_list' =>  $teacher_list,
    		), false);
    		$this->ct_template->render();

    	} catch (Exception $e) {
    		$this->ct_template->write('_title', '错误提示');
            $this->ct_template->write_view('content', 'errors/html/warn', array('msg'=>$e->getMessage() ), FALSE);
            $this->ct_template->render();
    	}
    }
    /**
     * 返回教师可用时间
     */
    public function teachertime(){
    	try {
    		$return = array('code'=>11,'mgs'=>'','list'=>'');
//     		$order_id = intval($this->input->get('order_id'));    //订单ID
//     		if(empty($order_id))throw new Exception('订单ID为空');
    
//     		$course_package_info = $this->IsHours($order_id); //验证课时
    
    		//session 取出已经选择的课程
//     		$this->load->library('session');
//     		$time_list = $this->session->time_list;
    
//     		//echo '<pre>';print_r($time_list);die();
    
//     		if($course_package_info['hours'] <= count($time_list))
//     			throw new Exception('您的课时已用完');
    
    			$this->load->helper("arraytool");   //加载工具
    			$teacher_id = intval($this->input->get('teacher_id'));    //获取园所ID
    			if(empty($teacher_id))throw new Exception('教师ID为空');
    
    			//获取教师时间段
    			$this->load->model('Teacher_Work_Time_model');
    			$where = array(
    					'teacher_id'=>$teacher_id,
    					'status'    =>  1,
    			);
    			$work_time = $this->Teacher_Work_Time_model->findAll($where,'work_week,work_time_start,work_time_end');
    			if(empty($work_time))throw new Exception('此教师未设置可用时间段');
    			$work_time = restByKey($work_time,'work_week',true);
    
    			$data_list = $this->getDateList(30);     //获取30天之后的时间
    
    			//合并
    			foreach ($data_list as $key=>$val){
    				if(!empty($work_time[$val['week']])){
    					$data_list[$key]['list'] = $work_time[$val['week']];
    				}
    			}
    
    			//获取该老师已预约的课程
    			$this->load->model('Book_model');
    			$where = "teacher_id = '$teacher_id' AND status IN (0,1)";
    			$book_list = $this->Book_model->findAll($where,'id,book_date,book_date_start,book_date_end');
    
    			//取出已选择课程session加入过滤
    			if(empty($book_list))$book_list = array();
    			if(empty($time_list))$time_list = array();
    			$book_list = array_merge($book_list,$time_list);
    
    			//echo '<pre>';print_r($book_list);die();
    			//过滤已经约课教师
    			if(!empty($book_list)){
    				foreach ($book_list as $val){
    					if(!empty($data_list[$val['book_date']]['list'])){
    						$work_time = $data_list[$val['book_date']]['list'];
    						foreach ($work_time as $key_work=>$val_work){
    							//结束课程的1小时，不可预约
    							if($val['book_date_start'] <= $val_work['work_time_start'] && date('H:i:s',strtotime($val['book_date_end'])+3600) >= $val_work['work_time_end']){
    								unset($data_list[$val['book_date']]['list'][$key_work]);
    							}
    						}
    					}
    				}
    			}
    
    			//过滤不存在的时间
    			foreach ($data_list as $key=>$val){
    				if(empty($val['list']))unset($data_list[$key]);
    			}
    			$return['code'] = 10;
    			$return['list'] = $this->load->view('purchasecourse/teacher_time_list',array(
    					'data_list'    =>  $data_list,
    			),true);;
    	}catch (Exception $e){
    		$return['msg'] = $e->getMessage();
    	}
    
    	echo json_encode($return);exit();
    }
    /**
     * 获取时间列表
     */
    private function getDateList($num = 30){
    	$data = array();
    	$weekArr=array("周日","周一","周二","周三","周四","周五","周六");
    	$date_d = date('d')+3;
    	for ($i=0;$i<$num;$i++){
    		$d = date('Y-m-d',mktime(0,0,0,date('m'),$date_d+$i,date('Y')));
    		$w = date('w',strtotime($d));
    		$data[$d] = array(
    				'date'  =>  $d,
    				'week'  =>  $w,
    				'week_name' =>  $weekArr[$w],
    		);
    	}
    	//排除节假日
    	$this->load->model('holiday_time_model');
    	$holiday_list = $this->holiday_time_model->findAll(array('status'=>1),'holiday');
    	if(!empty($holiday_list)){
    		$tmp = array();
    		foreach ($holiday_list as $key=>$val){
    			$tmp[] = $val['holiday'];
    		}
    		foreach ($data as $key=>$val){
    			if(in_array(mb_substr($key,5),$tmp))unset($data[$key]);
    		}
    	}
    	return $data;
    }
    /**
     * 判断该时间是否已经被预约
     */
    public function isteachertime(){
    	try {
    		$return = array('code'=>10,'mgs'=>'','list'=>'');
    		$this->load->library('session');
    		$time_list = $this->session->time_list;
    		if(empty($time_list))throw new Exception('时间列表获取失败');
    		$time_list_ = array();
    		foreach ($time_list as $val){
    			$time_list_[$val['book_date']][] = $val;
    		}
    		$time_list = $time_list_;
    		
    		$_date = mb_substr($set_date,0,10,'utf-8');
    		$_time = mb_substr($set_date,-11,11,'utf-8');
    		$_time = explode('~',$_time);
    		if(count($_time) != 2)throw new Exception('日期格式错误');
    		
    		
    		//生成数组入SESSION
    		$time_data[md5($set_date)] = array(
    				'book_date'     =>  $_date,
    				'book_date_start'   =>  date('H:i:s',strtotime($_time[0])),
    				'book_date_end'     =>  date('H:i:s',strtotime($_time[1])),
    		);
    		
    		
    		
    		$teacher_id = intval($this->input->get('hi_teacher_id'));   //教师ID
    		if(empty($teacher_id))throw new Exception('教师ID为空');
    
    		//获取该老师已预约的课程
    		$this->load->model('Book_model');
    		$where = "teacher_id = '$teacher_id' AND status IN (0,1)";
    		$book_list = $this->Book_model->findAll($where,'id,book_date,book_date_start,book_date_end');
    
    		//echo '<pre>';print_r($book_list);print_r($time_list);die();
    
    		//过滤已经约课教师
    		if(!empty($book_list)){
    			foreach ($book_list as $val){
    				if(!empty($time_list[$val['book_date']])){
    					$work_time = $time_list[$val['book_date']];
    					foreach ($work_time as $key_work=>$val_work){
    						//结束课程的1小时，不可预约
    						if($val['book_date_start'] <= $val_work['book_date_start'] && date('H:i:s',strtotime($val['book_date_end'])+3600) >= $val_work['book_date_end']){
    							throw new Exception($val['book_date'].' '.$val_work['book_date_start'].'~'.$val_work['book_date_end'].'的时间已被预约，请重新选择');
    						}
    					}
    				}
    			}
    		}
    	}catch (Exception $e){
    		$return['code'] = 11;
    		$return['msg'] = $e->getMessage();
    	}
    	echo json_encode($return);exit();
    }
}










